package com.gelapps.memogel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.webkit.WebView;

//TODO 			Ristrutturare la parte presa da http://android.marcoduff.com/aboutactivity.php
public class AboutActivity extends PreferenceActivity {
  
    
    /**
     * Listener EULA.
     * 
     * @author Marco "Duff" Palermo - www.marcoduff.com
     */
    public static interface OnStartupEulaListener {
            /**
             * Richiamata quando l'utente interagisce con la dialog di accettazione dell'EULA.
             * 
             * @param isAccepted Ha valore <code>true</code> se l'utente accetta l'EULA, <code>false</code> altrimenti.
             */
            public void onEulaAction(boolean isAccepted);
    }

    /**
     * Listener ChangeLog.
     * 
     * @author Marco "Duff" Palermo - www.marcoduff.com
     */
    public static interface OnStartupChangeLogListener {
            /**
             * Richiamata quando viene rilevato un cambio di versione mentre si visualizza la dialog di ChangeLog in avvio.
             * 
             * @param oldVersion La vecchia versione installata.
             * @param newVersion La nuova versione.
             */
            public void onVersionChanged(String oldVersion, String newVersion);
    }
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    extracted();
   
    }



	@SuppressWarnings("deprecation")
	private void extracted() {
		addPreferencesFromResource(R.xml.about_activity);
	}


    
    private boolean addPreferenceCategory(PreferenceScreen preferenceScreen, int titleResId, Preference... preferences) {
            boolean addPreference = false;
            for(Preference preference : preferences) {
                    if(preference!=null) addPreference = true;
            }
            if(addPreference) {
                    PreferenceCategory preferenceCategory = new PreferenceCategory(this);
                    preferenceCategory.setTitle(titleResId);
                    preferenceScreen.addPreference(preferenceCategory);
                    for(Preference preference : preferences) {
                            if(preference!=null) preferenceCategory.addPreference(preference);
                    }
                    return true;
            }
            else return false;
    }
    
    private Preference getPreferenceVersion() {
            String appName = getApplicationName(this);
    String currentVersion = getCurrentVersion(this);
    Preference versionPreference = new Preference(this);
    versionPreference.setTitle(appName);
   // versionPreference.setSummary(String.format(getString(R.string.aboutactivity_version), currentVersion));
    return versionPreference;
    }
    
    private static String getApplicationName(Context context) {
            ApplicationInfo applicationInfo = context.getApplicationInfo();
            return context.getString(applicationInfo.labelRes);
    }
    
    public static String getCurrentVersion(Context context) {
    try {
                    PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                    return packageInfo.versionName;
        }
        catch (NameNotFoundException e) {return "";}
    }
    
    private Preference getPreferenceFromStringExtra(String extra, int titleResId) {
    String extraValue = this.getIntent().getStringExtra(extra);
    if(extraValue!=null) {
            Preference preference = new Preference(this);
        preference.setTitle(titleResId);
        preference.setSummary(extraValue);
        return preference;
    }
    else return null;
    }
    
    private Preference getPreferenceFromUrlExtra(String extra, int titleResId, int summaryResId) {
    String url = this.getIntent().getStringExtra(extra);
    if(url!=null) {
            Preference preference = new Preference(this);
        preference.setTitle(titleResId);
        preference.setSummary(summaryResId);
        preference.setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        return preference;
    }
    else return null;
    }

    private Preference getPreferenceMarket(String extra, int titleResId, int summaryResId) {
    String flag = this.getIntent().getStringExtra(extra);
    if(flag!=null&&flag.equalsIgnoreCase("TRUE")) {
            Preference preference = new Preference(this);
        preference.setTitle(titleResId);
        preference.setSummary(summaryResId);
        preference.setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("market://details?id=%1$s", this.getPackageName()))));
        return preference;
    }
    else return null;
    }

    private Preference getPreferenceAuthorMarket(String extra, int titleResId, int summaryResId) {
    String authorMarket = this.getIntent().getStringExtra(extra);
    if(authorMarket!=null) {
            Preference preference = new Preference(this);
        preference.setTitle(titleResId);
        preference.setSummary(summaryResId);
        preference.setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("market://search?q=pub:%1$s", URLEncoder.encode(authorMarket)))));
        return preference;
    }
    else return null;
    }
    
    private Preference getPreferenceFromTwitterExtra(String extra, int titleResId, int summaryResId) {
    String twitterUsername = this.getIntent().getStringExtra(extra);
    if(twitterUsername!=null) {
            String url = String.format("http://www.twitter.com/%1$s", twitterUsername);
            Preference preference = new Preference(this);
        preference.setTitle(titleResId);
        preference.setSummary(summaryResId);
        preference.setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        return preference;
    }
    else return null;
    }
    
    private Preference getPreferenceFromMailExtra(String extra, int titleResId, int summaryResId) {
    String email = this.getIntent().getStringExtra(extra);
    if(email!=null) {
            String appName = getApplicationName(this);
            String currentVersion = getCurrentVersion(this);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("plain/text");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] {email});
            intent.putExtra(Intent.EXTRA_SUBJECT, String.format("New mail from %1$s v%2$s", appName, currentVersion));
            Preference preference = new Preference(this);
        preference.setTitle(titleResId);
        preference.setSummary(summaryResId);
        preference.setIntent(intent);
        return preference;
    }
    else return null;
    }
    
    private Preference getPreferenceFromRaw(String fileName, int titleResId, int summaryResId) {
            String data = getRawData(this, fileName);
            if(data!=null) {
            DialogPreference dialogPreference = new RawDialogPreference(this, titleResId, data);
            dialogPreference.setSummary(summaryResId);
            dialogPreference.setNegativeButtonText(null);
        return dialogPreference;
            }
            else {
                    return null;
            }
    }
    
    private static String getRawData(Context context, String fileName) {
            try {
                    String packageName = context.getApplicationContext().getPackageName();
                    Resources resources = context.getApplicationContext().getResources();
                    int resourceIdentifier = resources.getIdentifier(fileName, "raw", packageName); 
                    if(resourceIdentifier!=0) {
                            InputStream inputStream = resources.openRawResource(resourceIdentifier);
                            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                            String line;
                            StringBuffer data = new StringBuffer();
                            while((line=reader.readLine())!=null) {
                                    data.append(line);
                            }
                            reader.close();
                            return data.toString();
                    }
                    else return null;
            }
            catch(IOException e) {
                    return null;
            }
    }
    
    private class RawDialogPreference extends DialogPreference {
            private String data;
            
            public RawDialogPreference(Context context, int titleResId, String data) {
                    super(context, null);
            this.setTitle(titleResId);
            this.setDialogTitle(titleResId);
            this.data = data;
            }
            
            @Override
            protected void onPrepareDialogBuilder(Builder builder) {
                    super.onPrepareDialogBuilder(builder);
                    
                    WebView webView = new WebView(this.getContext());
                    webView.loadData(data, "text/html", "UTF-8");
                    
                    builder.setView(webView);
            }
    }
}
